package com.cs.beneficios.web.action;
import com.cs.beneficios.validator.Validaciones;
import com.cs.paoyer.administration.business.model.UserVO;
//import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForward;
//import org.apache.struts.action.ActionError;
//import org.apache.struts.action.ActionErrors;
import java.io.IOException;
import javax.servlet.ServletException;
import com.cs.beneficios.common.ConnectionFactory;

public class GuardarSedeAction extends Action
{
  /**
   * This is the main action called from the Struts framework.
   * @param mapping The ActionMapping used to select this instance.
   * @param form The optional ActionForm bean for this request.
   * @param request The HTTP Request we are processing.
   * @param response The HTTP Response we are processing.
   * @return 
   * @throws java.io.IOException
   * @throws javax.servlet.ServletException
   */
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
  {
    String valor1 = null, valor2 = null, valor3 = null, valor4 = null, valor5 = null;
    String valor6 = null, valor7 = null, valor8 = null, valor9 = null, valor10 = null, valor11 = null;
    Connection conn = null;  
    boolean existe = false;
    HttpSession session = request.getSession();
    //database db = new database();
    //ConnectionFactory cf = new ConnectionFactory("beneficios","beneficios");
	ConnectionFactory cf = new ConnectionFactory();
    Validaciones validacion = new Validaciones(cf);
    
   try{              
        conn = cf.getConnection();
        //conn = db.getConnectionWithDriver("beneficios","beneficios");
      }
      catch (SQLException e){
      }
      
    try
        {
          valor1 = request.getParameter("sede");
        }
      catch (Exception e){
          valor1 = "";
        }
        try
        {
          valor11 = request.getParameter("codsede");
        }
      catch (Exception e){
          valor11 = "";
        }
   try
        {
          valor2 = request.getParameter("descripcion");
        }
      catch (Exception e){
          valor2 = "";
        }  
     try
        {
          valor3 = request.getParameter("tipo");
        }
      catch (Exception e){
          valor3 = "";
        }
      try
        {
          valor4 = request.getParameter("caracter");
        }
      catch (Exception e){
          valor4 = "";
        }
     try
        {
          valor5 = request.getParameter("dirdescriptiva");
        }
      catch (Exception e){
          valor5 = "";
        }
      try
        {
          valor6 = request.getParameter("dirEncasillada");
        }
      catch (Exception e){
          valor6 = "";
        }
      try
        {
          valor7 = request.getParameter("cobama");
        }
      catch (Exception e){
          valor7 = "";
        }
      try
        {
          valor8 = request.getParameter("desde");
        }
      catch (Exception e){
          valor8 = "";
        }
      try
        {
          valor9 = request.getParameter("hasta");
        }
      catch (Exception e){
          valor9 = "";
        }
      try
        {
          valor10 = request.getParameter("municipio");
        }
      catch (Exception e){
          valor10 = "";
        }
        
        if (valor1 != null){
        existe = validacion.validasede(valor1.trim());
     }
 
 if (!existe){
      //Proceso para la auditoria
      UserVO user = (UserVO) request.getSession().getAttribute("userInfo");
      String terminalAddress = request.getRemoteAddr();
      String strTerminal = ("WEB="+terminalAddress);
      Calendar c = Calendar.getInstance(); 
      SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");   
      //Fin del proceso
            
       String strSql = " INSERT INTO TCS_BEN_SEDE ( CODIGO, NOMBRE, CARACTER, DIRECCION_DESCRIPTIVA,DESDE_VIGENCIA,HASTA_VIGENCIA, "+
                       " VIGENCIA,SEDE_CODIGO,DESCRIPCION,TIPO,DIRECCION_ENCASILLADA,LOCALIZACION_COBAMA,VFL_CODIGO_MUNICIPIO, "+
                       " usuario_crea, fecha_crea, terminal_crea, usuario_modifica, fecha_modifica, terminal_modifica) "+
                       " VALUES ( SCS_BEN_PRG.NEXTVAL,upper(?),upper(?),?,to_date(?,'yyyy-mm-dd'),to_date(?,'yyyy-mm-dd'),'A',?,?,?,?,?,?,?,to_date(?,'dd/mm/yyyy'),?,?,to_date(?,'dd/mm/yyyy'),?) ";
                 
      String strPar[] = {valor1.trim(),valor4,valor5,valor8,valor9,valor11,valor2,valor3,valor6,valor7,valor10,user.getName(), dateFormat.format(c.getTime()),strTerminal,user.getName(),dateFormat.format(c.getTime()),strTerminal};
      
      try{
           int insertar = cf.execSql(strSql,strPar,conn);
            if(insertar > 0)
          {
            session.setAttribute("mensajes","La Sede fue creada con Exito!!!");
            session.setAttribute("primeraVez",null);
          }
            }
           catch(SQLException e)
           {
			System.err.println("/******** TDSUB - cwsub");
			e.printStackTrace();
			System.err.println("TDSSPE - cwsub ********/");
             session.setAttribute("mensajes","La Sede no se pudo crear!!");
           }
            
        }else{
          session.setAttribute("mensajes","Ya existe una sede con ese nombre.");
      }
    return mapping.findForward("success");
  }
}